﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Common;
using DbControl;
using Models;
using LiveCharts;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using System.Windows.Controls;
using LiveCharts.Wpf;
using Separator = LiveCharts.Wpf.Separator;

namespace CentralMonitoring
{
    /// <summary>
    /// 数据查询窗体
    /// </summary>
    public partial class ViewChartForm : Form
    {
        public string mdeviceName;
        ChartValues<double> Wdlst = new ChartValues<double>();
        List<string> xTime = new List<string>();       
        public ViewChartForm()
        {
            InitializeComponent();
        }
        #region treeview
        private void InitTree()
        {
            this.treeView1.Nodes.Clear();
            DataTable dt = OprDevice.GetdevicesTree();
            if (dt != null && dt.Rows.Count > 0)
            {
                DataView dv = dt.DefaultView;
                dv.Sort = "parentid ASC";
                DataRowView[] arrDRV = dv.FindRows("0");
                if (arrDRV.Length == 0)
                    return;
                TreeNode tnNew = null;
                treeView1.BeginUpdate();
                foreach (DataRowView drv in arrDRV)
                {
                    tnNew = this.treeView1.Nodes.Add(drv["device_name"].ToString());
                    tnNew.Tag = drv.Row["id"];
                    CreateTreeNode(ref tnNew, dv);
                }
                treeView1.EndUpdate();
                treeView1.ExpandAll();
            }
        }
        private void CreateTreeNode(ref TreeNode tnParent, DataView dv)
        {
            DataRowView[] arrDrv = dv.FindRows(tnParent.Tag);
            if (arrDrv.Length == 0)
                return;
            TreeNode tnNew = null;
            foreach (DataRowView drv in arrDrv)
            {
                tnNew = tnParent.Nodes.Add(drv.Row["device_name"].ToString());
                tnNew.Tag = drv.Row["ID"].ToString();
                CreateTreeNode(ref tnNew, dv);

            }
        }
        private void treeView1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Point clickPoint = new Point(e.X, e.Y);
                TreeNode currentNode = treeView1.GetNodeAt(clickPoint);
                if (currentNode != null)
                {
                    treeView1.SelectedNode = currentNode;
                }
                else
                {
                    treeView1.SelectedNode = null;
                }
            }

        }
        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            int nodeId;
            if (e.Node.Nodes.Count > 0)
            {
                e.Node.Expand();
                nodeId = int.Parse(e.Node.Tag.ToString());
                treeView1.SelectedNode = e.Node;
                textBoxDevice.Text = e.Node.Text;
                parameters para = cmbParmI.SelectedItem as parameters;
                RefreshGrid(para);              
            }
            else
            {
                nodeId = int.Parse(e.Node.Tag.ToString());
                treeView1.SelectedNode = e.Node;
                textBoxDevice.Text = e.Node.Text;
                parameters para = cmbParmI.SelectedItem as parameters;
                RefreshGrid(para);
              
            }           
        }

        #endregion
        private void buttonFind_Click(object sender, EventArgs e)
        {
            parameters para=cmbParmI.SelectedItem as parameters;
            RefreshGrid(para);
        }
        private void InitCombox()
        {
            List<parameters> list = OprParameter.GetParameterAll();
            if (list != null && list.Count > 0)
            {
                cmbParmI.DisplayMember = "parameter_name";
                cmbParmI.ValueMember = "parameter_code";
                cmbParmI.DataSource = list;           
            }
            cmbParmI.SelectedIndex = 0; 
        }
        private void ViewChartForm_Load(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Maximized;
            dateTimePicker开始时间.Value = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 00:00:00"));
            dateTimePicker终止时间.Value = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 23:59:59"));
            InitCombox();
            InitTree();
            if (!string.IsNullOrEmpty(session.m_currentDeviceId))
            {
                devices dev = OprDevice.GetDeviceByDeviceId(session.m_currentDeviceId);
                textBoxDevice.Text = dev.device_name.ToString();
            }
            cmbParmI.SelectedIndex = 0;
            parameters para=this.cmbParmI.SelectedItem as parameters;
            RefreshGrid(para);
      
          
            this.StatusLabel0.Text = string.Format("系统时间：{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
        }
        private void RefreshGrid(parameters paraI)
        {
            string filter = "";
            if (!string.IsNullOrEmpty(textBoxDevice.Text))
            {
                filter = textBoxDevice.Text;
            }
            string strParaI = paraI.parameter_code;            
            try
            {
                DataTable dt = OprUI.GetSensorDatasByDeviceNameAndPara(dateTimePicker开始时间.Value, dateTimePicker终止时间.Value, filter, strParaI);
                if (dt != null)
                {
                    xTime.Clear();
                    Wdlst.Clear();                  
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            double dmtmp = 0;
                            xTime.Add(((DateTime)dt.Rows[i][1]).ToString("yyyy-MM-hh HH:mm:dd")); 
                            if (!string.IsNullOrEmpty(dt.Rows[i][2].ToString()))
                                dmtmp = double.Parse(dt.Rows[i][2].ToString());
                            else
                                dmtmp = 0;
                            Wdlst.Add(dmtmp);                           
                        }
                    }
                    else
                    {
                        for (int i = 0; i < 60; i++)
                        {
                            DateTime time = this.dateTimePicker终止时间.Value.AddMinutes(i-60);                           
                            xTime.Add(time.ToString("yyyy-MM-dd HH:mm:ss"));
                            Wdlst.Add(0);
                        }
                    }
                    string strTemp = paraI.parameter_name;
                    ReLoadChart(strTemp);
                }
            }
            catch (Exception ex)
            {
                lLogWrite.WriteLog(ex.ToString());
            }            
        }        
        private void ReLoadChart(string NameI)
        {
            cartesianChart1.DisableAnimations = true;
            cartesianChart1.Series.Clear();
            cartesianChart1.AxisY.Clear();
            cartesianChart1.AxisX.Clear();
            cartesianChart1.Series.Add(new LineSeries
            {
                Values = Wdlst,
                //DataLabels = true,
                Title = NameI,
                LineSmoothness = 1,
                LabelPoint = (point => point.Y.ToString()),
                ScalesYAt = 0
            });           

            cartesianChart1.AxisY.Add(new Axis
            {
                Foreground = System.Windows.Media.Brushes.IndianRed,
                Title = NameI,
                MinValue =0,
                ShowLabels = true,
                //MaxValue = Wdlst.Max()+1,
                //Position = AxisPosition.RightTop,
            });           
            cartesianChart1.AxisX.Add(new Axis
            {
                Labels =xTime,                
                LabelsRotation = 20,
                ShowLabels = true,
                Separator=new Separator { Step=3}
            });

        }

        private void buttonExp_Click(object sender, EventArgs e)
        {
            try
            {
                Export();
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据导出失败:" + ex.ToString());
            }
        }
        private void Export()
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Title = "保存为图片文件";
            dlg.Filter = "jpg图片(*.JPG)|*.JPEG|png图片(*.PNG)|*.PNG|jpeg图片(*.JPEG)|*.JPEG";
            dlg.FilterIndex = 1;
            dlg.RestoreDirectory = true;
            dlg.CreatePrompt = true; 
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                //FileStream fs=new FileStream(dlg.FileName, FileMode.Create);
                //RenderTargetBitmap bmp=new RenderTargetBitmap((int)cartesianChart1.Width+10,(int)cartesianChart1.Height+10,96,96,PixelFormats.Pbgra32);
                //var viewbox=new Viewbox();
                //viewbox.Child = cartesianChart1;
                //bmp.Render(viewbox);
                //BitmapEncoder encoder = new PngBitmapEncoder();
                //encoder.Frames.Add(BitmapFrame.Create(bmp));
                //encoder.Save(fs);
                //fs.Close();
                //fs.Dispose();
                using (var bmp=new Bitmap(cartesianChart1.Width,cartesianChart1.Height))
                {
                    cartesianChart1.DrawToBitmap(bmp,new Rectangle(0,0,cartesianChart1.Width,cartesianChart1.Height));
                    bmp.Save(dlg.FileName);
                    MessageBox.Show(this, "保存图片成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }                
            }
    }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        

        private void timer1_Tick(object sender, EventArgs e)
        {
            this.StatusLabel0.Text = string.Format("系统时间：{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
        }
    }
}
